package cn.iocoder.yudao.module.wrzj.controller.app.conversation;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wrzj.controller.app.BaseWrzjController;
import cn.iocoder.yudao.module.wrzj.controller.app.conversation.vo.AppConversationPageReqVO;
import cn.iocoder.yudao.module.wrzj.controller.app.conversation.vo.AppConversationRespVO;
import cn.iocoder.yudao.module.wrzj.controller.app.conversation.vo.AppConversationSaveReqVO;
import cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser.vo.AppWrzjChatbaseSendMsgVO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.conversation.ConversationDO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.greatman.GreatmanDO;
import cn.iocoder.yudao.module.wrzj.service.conversation.ConversationService;
import cn.iocoder.yudao.module.wrzj.service.greatman.GreatmanService;
import cn.iocoder.yudao.module.wrzj.service.wrzjuser.WrzjUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Comparator;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 APP - chatbase会话记录")
@RestController
@RequestMapping("/wrzj/chatbase/conversation")
@Validated
public class AppConversationController extends BaseWrzjController {

    @Resource
    private ConversationService conversationService;

    @Resource
    private GreatmanService greatmanService;

    @Resource
    private WrzjUserService wrzjUserService;


    //    private static String CHATBOT_ID = "q1YRL6l72cgvQ_uC41El2";
    private static String CHATBASE_APIKEY = "9e2de453-9580-4aed-a73d-04fee5ed4fbc";

    /**
     * 会话id目前不存入数据库，默认算法为：用户id_伟人id，拼接字符串的加密值
     *
     * @param greatmanId
     * @return
     */
    @GetMapping("/getConversation")
    @Operation(summary = "获取会话数据")
    public CommonResult<String> getConversationId(String greatmanId) {
        return success(convertConversationId(greatmanId));
    }

    public static void main(String[] args) {
        JSONObject requestJson = new JSONObject();
        JSONArray msgArr = new JSONArray();
        JSONObject msgObj1 = new JSONObject();
        msgObj1.put("content", "asdfsfsdfsdfsdfsdfsdfsd");
        msgObj1.put("role", "assistant");
        JSONObject msgObj2 = new JSONObject();
        msgObj2.put("content", "nskcnsd dskfndskfnsd" +
                "sdfdsfsdfdsfsd" +
                "fdgfdgdfgd");
        msgObj2.put("role", "user");
        msgArr.add(msgObj1);
        msgArr.add(msgObj2);
        requestJson.put("messages", msgArr);
        requestJson.put("chatbotId", "q1YRL6l72cgvQ_uC41El2");
        requestJson.put("stream", false);
        requestJson.put("temperature", 0);
        requestJson.put("model", "gpt-4o");
        requestJson.put("conversationId", "730587179e5e9611d4e74f135374d8fe");
        System.out.println(requestJson.toJSONString());
    }

    @PostMapping("/chat")
    @Operation(summary = "发送消息")
    public CommonResult<AppConversationRespVO> chat(@Valid @RequestBody AppWrzjChatbaseSendMsgVO sendMsgVO) {
        GreatmanDO greatmanDO = greatmanService.getGreatman(Integer.parseInt(sendMsgVO.getGreatmanId()));
        String conversationId = convertConversationId(sendMsgVO.getGreatmanId());
        AppConversationSaveReqVO userConversation = AppConversationSaveReqVO.builder()
                .uid(String.valueOf(getLoginUid()))
                .role("user")
                .content(sendMsgVO.getContent())
                .conversationId(conversationId)
                .chatbotId(greatmanDO.getChatbase())
                .build();
        conversationService.createConversation(userConversation);

        //获取上下文对话信息
        ConversationDO lastedAssistantChat = conversationService.getLastedAssistantChat(conversationId);
        String contextChatMsg = "";
        if (lastedAssistantChat != null) {
            contextChatMsg = lastedAssistantChat.getContent().replace(" ", "").replace("\n", "");
        }

        String json = "{\n" +
                "  \"messages\": [\n" +
                "    { \"content\": \"" + contextChatMsg + "\", \"role\": \"assistant\" },\n" +
                "    { \"content\": \"" + sendMsgVO.getContent() + "\", \"role\": \"user\" }\n" +
                "  ],\n" +
                "  \"chatbotId\": \"" + greatmanDO.getChatbase() + "\",\n" +
                "  \"stream\": false,\n" +
                "  \"temperature\": 0,\n" +
                "  \"model\": \"gpt-4o\",\n" +
                "  \"conversationId\": \"" + conversationId + "\"\n" +
                "}";

        JSONObject requestJson = new JSONObject();
        JSONArray msgArr = new JSONArray();
        JSONObject msgObj1 = new JSONObject();
        msgObj1.put("content", contextChatMsg);
        msgObj1.put("role", "assistant");
        JSONObject msgObj2 = new JSONObject();
        msgObj2.put("content", sendMsgVO.getContent());
        msgObj2.put("role", "user");
        msgArr.add(msgObj1);
        msgArr.add(msgObj2);
        requestJson.put("messages", msgArr);
        requestJson.put("chatbotId", greatmanDO.getChatbase());
        requestJson.put("stream", false);
        requestJson.put("temperature", 0);
        requestJson.put("model", "gpt-4o");
        requestJson.put("conversationId", conversationId);

        System.out.println("request:" + requestJson.toJSONString());
        String result = HttpRequest.post("https://www.chatbase.co/api/v1/chat")
                .body(requestJson.toJSONString())
                .header("Authorization", "Bearer " + CHATBASE_APIKEY)
                .execute().body();
        System.err.println("reslut:" + result);
        JSONObject answerJson = JSONObject.parseObject(result);
        String answerContent = answerJson.getString("text");

        if (StrUtil.isEmpty(answerContent)) {
            answerContent = result;
            if(StrUtil.isNotEmpty(answerJson.getString("error"))) {
                JSONObject obj = JSONObject.parseObject(answerJson.getString("error"));
                answerContent = obj.getString("message");
            }
        }

        AppConversationSaveReqVO assistantConversation = AppConversationSaveReqVO.builder()
                .uid(String.valueOf(getLoginUid()))
                .role("assistant")
                .content(answerContent)
                .conversationId(conversationId)
                .chatbotId(greatmanDO.getChatbase())
                .build();
        int id = conversationService.createConversation(assistantConversation);

        if (answerContent.contains("【") && answerContent.contains("】")) {
            String score = answerContent.substring(answerContent.lastIndexOf("【") + 1, answerContent.lastIndexOf("】"));
            System.out.println("score:" + score);
            int socre = Integer.parseInt(score);
            wrzjUserService.addGreatmanScore(getLoginUid(), Long.valueOf(sendMsgVO.getGreatmanId()), socre);
            System.out.println("=========本次伟人增加好感度：" + score);
        }

        return success(BeanUtils.toBean(conversationService.getConversation(id), AppConversationRespVO.class));
    }

    @PostMapping("/create")
    @Operation(summary = "创建chatbase会话记录")
    public CommonResult<Integer> createConversation(@Valid @RequestBody AppConversationSaveReqVO createReqVO) {
        return success(conversationService.createConversation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新chatbase会话记录")
    public CommonResult<Boolean> updateConversation(@Valid @RequestBody AppConversationSaveReqVO updateReqVO) {
        conversationService.updateConversation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除chatbase会话记录")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteConversation(@RequestParam("id") Integer id) {
        conversationService.deleteConversation(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得chatbase会话记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppConversationRespVO> getConversation(@RequestParam("id") Integer id) {
        ConversationDO conversation = conversationService.getConversation(id);
        return success(BeanUtils.toBean(conversation, AppConversationRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得chatbase会话记录分页")
    public CommonResult<PageResult<AppConversationRespVO>> getConversationPage(@Valid AppConversationPageReqVO pageReqVO) {
        pageReqVO.setConversationId(convertConversationId(pageReqVO.getGreatmanId()));
        pageReqVO.setUid(String.valueOf(getLoginUid()));
        PageResult<ConversationDO> pageResult = conversationService.getConversationPage(pageReqVO);
        pageResult.getList().sort(Comparator.comparingInt(ConversationDO::getId));
        return success(BeanUtils.toBean(pageResult, AppConversationRespVO.class));
    }


}
